package im430.santashelper.dao.mybatis;

import im430.santashelper.business.Child;
import im430.santashelper.business.Gift;
import im430.santashelper.dao.AddressDAO;
import im430.santashelper.dao.ChildDAO;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;

public class ChildDAOImpl implements ChildDAO {

	private SqlSession sqlSession;
	private AddressDAO addressDAO;

	private final int ADDRESS_NOWHERE_ID = 1;

	public void addChild(Child child) {

		if (child.getAddress() == null) {
			child.setAddress(getAddressDAO().getAddressById(ADDRESS_NOWHERE_ID));
		} else if (child.getAddress().getId() < 0) {
			getAddressDAO().addAddress(child.getAddress());
		}
		
		getSqlSession().insert("im430.santashelper.dao.mybatis.ChildDAOImpl.addChild", child);

	}

	public void updateChild(Child child) {
		getSqlSession().update("im430.santashelper.dao.mybatis.ChildDAOImpl.updateChild", child);
	}

	public void removeChild(Child child) {
		getSqlSession().delete("im430.santashelper.dao.mybatis.ChildDAOImpl.removeChild", child);
	}

	public Child getChildById(int id) {
		return getSqlSession().selectOne("im430.santashelper.dao.mybatis.ChildDAOImpl.getChildById", id);
	}

	public List<Child> getAllChildren() {
		return getSqlSession().selectList("im430.santashelper.dao.mybatis.ChildDAOImpl.getAllChildren");
	}

	public SqlSession getSqlSession() {
		return sqlSession;
	}

	@Autowired
	public void setSqlSession(SqlSession sqlSession) {
		this.sqlSession = sqlSession;
	}

	public AddressDAO getAddressDAO() {
		return addressDAO;
	}

	@Autowired
	public void setAddressDAO(AddressDAO addressDAO) {
		this.addressDAO = addressDAO;
	}

	@Override
	public void addGift(Child child, Gift gift) {
		Map<String,Object> m = new HashMap<String, Object>();
		m.put("gift", gift);
		m.put("childId", child.getId());
		getSqlSession().insert("im430.santashelper.dao.mybatis.ChildDAOImpl.addGift", m);
	}

	@Override
	public Gift getGiftById(int id) {
		return getSqlSession().selectOne("im430.santashelper.dao.mybatis.ChildDAOImpl.getGiftById", id);
	}

	@Override
	public void updateGift(Gift gift) {
		getSqlSession().update("im430.santashelper.dao.mybatis.ChildDAOImpl.updateGift", gift);
	}
	
	@Override
	public int getChildIdFromGift(Gift gift) {
		return getSqlSession().selectOne("im430.santashelper.dao.mybatis.ChildDAOImpl.getChildIdFromGift", gift);
	}
	
	@Override
	public void removeGift(Gift gift) {
		getSqlSession().delete("im430.santashelper.dao.mybatis.ChildDAOImpl.removeGift", gift);
	}

}